import {websocketUrl} from '@/libs/baseUrl'
import {message} from '@/libs/global/antDesignVue'

interface UseWebSocketOption {}

function useWebSocket<T = WebSocketReplyData, K = WebSocketSendData>(option: {
  onmessage: (e: T) => void
  onopen: (e: Event) => void
}) {
  const webSocket = ref<WebSocket>()

  // 心跳包
  const heartBeatInterval = 20 //心跳包间隔时间 单位（s）
  const heartBeatTimer = ref<NodeJS.Timer>()

  // 状态
  const isRefresh = ref(false)

  function connectWebSocket() {
    initStatus()

    if ('WebSocket' in window) {
      webSocket.value = new WebSocket(websocketUrl) //连接SockJS的endpoint名称为"bullet"
      console.log('webscoket连接地址："' + websocketUrl + '" \n', webSocket.value)

      /**
       * 挂载onopen事件
       * @desc 用来处理第一次连接上websocket服务器的事件
       * */
      webSocket.value.onopen = option.onopen

      /**
       * 挂载onmessage事件
       * @desc 用来处理服务器返回的数据
       * */
      webSocket.value.onmessage = e => {
        option.onmessage(JSON.parse(e.data) as T)
      }

      /**
       * 挂载onerror事件
       * @desc 用来处理websocket传输期间异常错误
       * */
      webSocket.value.onerror = onerror

      /**
       * 挂载onclose事件
       * @desc websocket断开的回调
       * */
      webSocket.value.onclose = onclose

      return true
    } else {
      console.error('not have WebSocket')
      message.error('此浏览器不支持webSocket')
      return false
    }
  }

  /**
   * 关闭连接，关闭后停止发送心跳包
   * @param e
   */
  function onclose(e: CloseEvent) {
    console.log('websocket断开', e)

    !webSocket.value && (webSocket.value = undefined)
    closeHearBeat()

    if (isRefresh.value) {
      connectWebSocket()
    }
  }

  function onerror(err: Event) {
    console.error('websocket错误', err)
    // if (err.reconnectNum === 4) {
    //   console.log('服务器错误，无法连接服务器请稍微再试')
    // }
  }

  function sendMessage(message: K) {
    if (webSocket.value) {
      webSocket.value.send(JSON.stringify(message))
    }
  }

  function closeWebSocket() {
    if (webSocket.value) {
      webSocket.value.close()
      webSocket.value = undefined
    }
  }

  function openHeartBeat(data: K) {
    closeHearBeat()
    heartBeatTimer.value = setInterval(() => {
      sendMessage(data)
    }, heartBeatInterval * 1000)
  }

  function closeHearBeat() {
    if (heartBeatTimer.value) clearInterval(heartBeatTimer.value)
  }

  function hangleMessage() {}

  function refreshWebSocket() {
    closeWebSocket()
    isRefresh.value = true
    connectWebSocket()
  }

  function initStatus() {
    isRefresh.value = false
  }

  return {
    webSocket,
    connectWebSocket,
    closeWebSocket,
    sendMessage,
    openHeartBeat,
    refreshWebSocket
  }
}

export default useWebSocket
